define(window.backboneCommon.getViewDefine("creative.material"), function ($,require,Collection,tpl) {
    var defaultsOptions={
        parentElementId:"",
        campaignId:"",
        url:"",
        selectJson:{},
        selectList:[],
        list:"",
        filter:"",
        changeTabCallback:null,
        uploadImgCallback:null,
        isDisabled:false
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {},
        initialize: function () {
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={};
            this.extObject={};
            this.pageData={};
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            this.pageOptions.campaignId=parseInt(this.pageOptions.campaignId);
        },
        initValue:function (list,json) {
            this.pageOptions=$.ExtCommon.initMergeJson(this.pageOptions,{selectList:list,selectJson:json});
        },

        //非原生
        initDefault:function (json) {
            this.pageOptions=$.ExtCommon.initMergeJson(this.pageOptions,json);
            this._mergeValueDefault();
            if(!$.ExtCommon.isCheckEmpty(this.pageOptions.list)){
                $(this.pageOptions.parentElementId).html($("#template_material_file").render(this.pageOptions.list));
                this._initAssembly();
            }else{
                $(this.pageOptions.parentElementId).html("");
            }
        },
        _mergeValueDefault:function () {
            var self=this;
            $.each(self.pageOptions.list,function (i,info) {
                if(self.pageOptions.selectJson.hasOwnProperty(info.tSpecId)){
                    var cmInfo=self.pageOptions.selectJson[info.tSpecId];
                    info.updId=cmInfo.id;
                    if(info.isImage){
                        info.imgId=cmInfo.imgId;
                        info.urlValue=cmInfo.urlValue;
                    }else{
                        info.textValue=cmInfo.textValue;
                    }
                }
                info.isRequired=false;
            });
        },

        //原生
        initNative:function (json) {
            var self=this;
            this.pageOptions=$.ExtCommon.initMergeJson(this.pageOptions,json);
            var filterData=this._getFilterData(this.pageOptions.list,this.pageOptions.filter);
            var list=[];
            if(!$.ExtCommon.isCheckEmpty(filterData.parent["0"])){
                $.each(filterData.parent["0"],function (i,info) {
                    var newInfo={index:i,tSpecId:info.tSpecId,tabName:info.elementName,isStruct:info.isStruct,tipMsg:info.tipMsg,list:[]};
                    if(info.isStruct){
                        var listStructure=self._getStructure(info,filterData);
                        if(listStructure.length>0){
                            newInfo.list=listStructure;
                            list.push(newInfo);
                        }
                    }else{
                        var cInfo=$.ExtCommon.getJsonClone(info);
                        cInfo.groupIndex=1;
                        cInfo.isRequiredIcon=cInfo.isRequired;
                        self._mergeValueNative(cInfo);
                        newInfo.list.push(cInfo);
                        list.push(newInfo);
                    }
                });
            }
            this.pageData.filterData=filterData;
            this.pageData.tabsList=list;
            if(!$.ExtCommon.isCheckEmpty(list)){
                $(this.pageOptions.parentElementId).html($("#template_material_native_detail").render({list:list}));
                this._initAssembly();
            }else{
                $.ExtNotify.error("该广告位暂无该标的物的素材数据");
                $(this.pageOptions.parentElementId).html("");
            }
        },
        _getFilterData:function (list,filter) {
            var json={};
            var parent={};
            $.each(list,function (i,info) {
                if(info.arrFilter.length===0|| $.ExtCommon.isCheckEmpty(filter) ||info.arrFilter.indexOf(filter)>-1){
                    if(!parent.hasOwnProperty(info.parentId)){parent[info.parentId]=[]}
                    json[info.tSpecId]=info;
                    parent[info.parentId].push(info);
                }
            });
            return {json:json,parent:parent};
        },
        _getStructure:function (info,filterData) {
            var list=[];
            if(filterData.parent.hasOwnProperty(info.tSpecId)){
                var self=this;
                var cList=filterData.parent[info.tSpecId];
                if(info.maxOccurs>1){
                    for(var ci=0;ci<info.maxOccurs;ci++){
                        if(cList.length===1){
                            var newCInfo=$.ExtCommon.getJsonClone(cList[0]);
                            newCInfo.groupIndex=ci+1;
                            newCInfo.isRequiredIcon=false;
                            self._mergeValueNative(newCInfo);
                            list.push(newCInfo);
                        }
                    }
                }else{
                    $.each(cList,function (i,cInfo) {
                        var newCInfo=$.ExtCommon.getJsonClone(cInfo);
                        newCInfo.groupIndex=1;
                        newCInfo.isRequiredIcon=newCInfo.isRequired;
                        self._mergeValueNative(newCInfo);
                        list.push(newCInfo);
                    });
                }
            }
            return list;
        },
        _mergeValueNative:function (info) {
            var key=info.tSpecId+"-"+info.groupIndex.toString();
            if(this.pageOptions.selectJson.hasOwnProperty(key)){
                var cmInfo=this.pageOptions.selectJson[key];
                info.updId=cmInfo.id;
                if(info.isImage){
                    info.imgId=cmInfo.imgId;
                    info.urlValue=cmInfo.urlValue;
                }else{
                    info.textValue=cmInfo.textValue;
                }
            }
        },
        //过滤
        initFilterNative:function (filter) {
            this.initNative({filter:filter});
        },
        //控件初始化
        _initAssembly:function () {
            var self=this;
            if(self.pageOptions.changeTabCallback){
                $(self.pageOptions.parentElementId).find("a[data-toggle='tab']").on("shown.bs.tab",function () {
                    self.pageOptions.changeTabCallback()
                });
            }
            this._initUpLoadImg();
            if(this.pageOptions.changeTabCallback){this.pageOptions.changeTabCallback()}
            if(self.pageOptions.isDisabled){
                $(this.pageOptions.parentElementId).find(":text").prop("disabled", true);
            }
        },
        _initUpLoadImg:function() {
            var self=this;
            $.each($(self.pageOptions.parentElementId).find(".init-file"),function (i,item) {
                var element = $(item);
                var thisData = element.data();
                element.removeClass("init-file");
                var width=thisData["imgWidth"];
                var height=thisData["imgHeight"];
                element.ExtUploadFile({
                    "tipmsg_top": thisData["msgtipTop"],
                    "tipmsg_bottom": thisData["msgtipBottom"],
                    maxSize: thisData["imgSize"],
                    imgSrcUrl: thisData["url"],
                    sizeWidth:parseInt(width),
                    sizeHeight:parseInt(height),
                    spanWidth:"490",
                    icon_remove:self.pageOptions.isDisabled?null:"fa fa-times",
                    infoExt:{fileType:thisData["fileFormat"],
                        clickCallback:function () {
                            return !self.pageOptions.isDisabled
                        }
                    },
                    beforeRemoveCallback: function (obj) {
                        obj.siblings(".box-file").removeData("url").removeData("imgId");
                    },
                    ajaxInfoCallback: {
                        url: self.pageOptions.url,
                        data:{width:width,height:height,campaignId:self.pageOptions.campaignId},
                        success: function (element, resData) {
                            element.data({url:resData["imageUrl"],imgId:resData["imageId"]});
                            if(self.pageOptions.uploadImgCallback){self.pageOptions.uploadImgCallback(element)}
                        }
                    }
                });
            });
        },

        getHtmlValueDefault:function () {
            var list=[];
            $.each($(this.pageOptions.parentElementId).find(":file"),function (i,item) {
                var elData=$(item).data();
                if(!$.ExtCommon.isCheckEmpty(elData.url)){
                    var tempJson={tSpecId:elData.tSpecId,imgId:elData.imgId};
                    if(!$.ExtCommon.isCheckEmpty(elData.updId)){tempJson.updId=elData.updId}
                    list.push(tempJson);
                }
            });
            return list;
        },
        checkDefault:function () {
            var list=this.getHtmlValueDefault();
            var isCheck=true;
            if($.ExtCommon.isCheckEmpty(list)){
                isCheck=false;
                $.ExtNotify.error("请上传创意素材");
            }
            return isCheck;
        },

        getHtmlValueNative:function () {
            var list=[];
            $.each($(this.pageOptions.parentElementId).find(".tab-pane"),function(i,item){
                var elementTab=$(item);
                var tempParent={tSpecId:elementTab.data("tSpecId"),list:[]};
                $.each(elementTab.find(".native-element :input"),function(j,itemInput){
                    var element=$(itemInput);
                    var elData=element.data();
                    var tempJson;
                    switch (element.attr("type")){
                        case "text":
                            var materialText=$.trim(element.val());
                            if(!$.ExtCommon.isCheckEmpty(materialText)){
                                tempJson={tSpecId: elData.tSpecId,isText:true,textValue: materialText,isRequired:elData.isRequired};
                            }
                            break;
                        case "file":
                            if(!$.ExtCommon.isCheckEmpty(elData.url)){
                                tempJson= {tSpecId:elData.tSpecId,isImage:true,imgId:elData.imgId,isRequired:elData.isRequired}
                            }
                            break;
                    }
                    if(!$.ExtCommon.isCheckEmpty(tempJson)){
                        tempJson.groupIndex=elData.groupIndex;
                        if(!$.ExtCommon.isCheckEmpty(elData.updId)) tempJson.updId=elData.updId;
                        tempParent.list.push(tempJson)
                    }
                });
                list.push(tempParent);
            });
            return list;
        },
        checkNative:function () {
            var self=this;
            var msg=[];
            var msgArrId=[];
            var listValue=this.getHtmlValueNative();
            if(listValue.length>0){
                $.each(listValue,function (i,info) {
                    var mInfo=self.pageData.filterData.json[info.tSpecId];
                    var pInfo=self.pageData.filterData.parent[info.tSpecId];
                    if(mInfo.isStruct){
                        if(mInfo.maxOccurs>1){
                            if(pInfo.length===1){
                                if(info.list.length<mInfo.minOccurs){
                                    if(msgArrId.indexOf(info.tSpecId)===-1){
                                        msgArrId.push(info.tSpecId);
                                        msg.push({tSpecId:info.tSpecId,msg:"素材设置中"+mInfo.elementName+"："+mInfo.tipMsg});
                                    }
                                }
                            }
                        }else{
                            var pr=$.ExtCommon.getListInfoByPara(pInfo,{isRequired:true});
                            var ir=$.ExtCommon.getListInfoByPara(info.list,{isRequired:true});
                            if(pr.length!==ir.length){
                                if(msgArrId.indexOf(info.tSpecId)===-1){
                                    msgArrId.push(info.tSpecId);
                                    msg.push({tSpecId:info.tSpecId,msg:"素材设置中"+mInfo.elementName+"：填写信息不完全"});
                                }
                            }
                        }
                    }else{
                        if(mInfo.isRequired && info.list.length===0){
                            if(msgArrId.indexOf(info.tSpecId)===-1){
                                msgArrId.push(info.tSpecId);
                                msg.push({tSpecId:info.tSpecId,msg:"素材设置中"+mInfo.elementName+"：填写信息不完全"});
                            }
                        }
                    }
                });
                $.each($(self.pageOptions.parentElementId).find(".tab-pane"),function(i,item){
                    var elementTab=$(item);
                    var tSpecId=elementTab.data("tSpecId");
                    var mInfo=self.pageData.filterData.json[tSpecId];
                    var pInfo=self.pageData.filterData.parent[tSpecId];
                    if(mInfo.isStruct){
                        if(mInfo.maxOccurs>1 && pInfo.length===1){
                            elementTab.find(".native-element :input").removeAttr("required");
                        }
                    }
                    $.each(elementTab.find(".native-element :input"),function(j,itemInput){
                        var element=$(itemInput);
                        if(element.attr("type")==="file" && !$.ExtCommon.isCheckEmpty(element.data("url"))){element.removeAttr("required")}
                        if(!element.parsley().isValid()){
                            if(msgArrId.indexOf(tSpecId)===-1){
                                msgArrId.push(tSpecId);
                                msg.push({tSpecId:tSpecId,msg:"素材设置中"+mInfo.elementName+"：填写信息不完全"});
                            }
                        }
                    });
                });
            }else{
                msg.push({msg:"请上传创意素材"});
            }

            if(msg.length>0){
                var msgInfo=msg[0];
                if(msgInfo.tSpecId){
                    $(self.pageOptions.parentElementId).find("a[href='#tab_native_"+msgInfo.tSpecId+"']").tab('show');
                }
                $.ExtNotify.error(msgInfo.msg);
            }
            return msg
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        initValue:function (list,json) {
            this.view.initValue(list,json);
        },
        initDefault:function (list) {
            this.view.initDefault(list);
        },
        initNative:function (json) {
            this.view.initNative(json);
        },
        initFilter:function (filter) {
            this.view.initFilterNative(filter);
        },
        getValueDefault:function () {
            return this.view.getHtmlValueDefault();
        },
        checkDefault:function () {
            return this.view.checkDefault();
        },
        getValueNative:function () {
            return this.view.getHtmlValueNative();
        },
        checkNative:function () {
            return this.view.checkNative();
        }
    };
    return viewModel;
});